#include "authdialog.h"
#include "ui_authdialog.h"

authdialog::authdialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::authdialog)
{
    ui->setupUi(this);
    QUrl vk_authurl("http://api.vk.com/oauth/authorize?client_id=2620679&redirect_uri=http://api.vk.com/blank.html&scope=audio&display=wap&response_type=token");
    ui->webView->load(vk_authurl);
    manager = new QNetworkAccessManager();
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(getAudioList(QNetworkReply*)));
    connect(ui->webView,SIGNAL(loadFinished(bool)),this,SLOT(load_list()));
}

authdialog::~authdialog()
{
    delete ui;
}

void authdialog::getAudioList(QNetworkReply *reply)
{
    QByteArray byte; //
    byte = reply->readAll(); //
    //ui->textEdit->setText(QString(byte)); //
    //
    delete request; //  .
    request = NULL; //
    QFile file("audio.xml");
    file.open(QIODevice::WriteOnly); //
    if(file.isOpen())
    {
        file.write(QString(byte).toLatin1().data());
    }
    file.close(); //
    reply->deleteLater(); //  ,   ,  ,
    this->close();
}

void authdialog::load_list()
{
    QString token_text = ui->webView->page()->mainFrame()->toPlainText();
    int length = token_text.length();
    QString symbol = "&";
    QString token = token_text.left(12);
    if (token == "access_token")
    {
        token = "";
        for (int i=13;i<=length;i++)
        {
            QString symbol_token = QVariant(token_text[i]).toString();
            if (symbol_token == symbol)
            {
                break;
            }
            token += token_text[i];
        }
        QUrl vk_audio("https://api.vkontakte.ru/method/audio.get.xml?&access_token="+token);
        request =new QNetworkRequest(vk_audio);
        manager->get(*request);
        ui->webView->hide();
    }
}
